package com.scott.distrubutelock.javaapi;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author Scott 2017/11/2 18:02
 */
public class ZookeeperClient {

    /**
     * zookeeper 连接字符串
     */
    private final static String CONNECT_STRING = "192.168.1.113:2181,192.168.11.104:2181";

    /**
     * 超时时间
     */
    private final static int SESSION_TIME_OUT = 5000;

    /**
     * create zookeeper connection
     * @return {@link ZooKeeper}
     * @throws IOException 异常
     * @throws InterruptedException 异常
     */
    public static ZooKeeper getInstance() throws IOException, InterruptedException {
        final CountDownLatch countDownLatch = new CountDownLatch(1);

        ZooKeeper zooKeeper = new ZooKeeper(CONNECT_STRING, SESSION_TIME_OUT, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getState() == Event.KeeperState.SyncConnected) {
                    countDownLatch.countDown();
                }
            }
        });

        countDownLatch.await();
        return zooKeeper;
    }

    /**
     * 获取统一会话超时时间
     * @return String
     */
    public static int getSessionTimeOut(){
        return SESSION_TIME_OUT;
    }
}
